﻿using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using ServerSide.Common;
using ServerSide.EFCoreContext;
using ServerSide.Model;
using ServerSide.Model.Dto.UserDto;
using ServerSide.Model.Other;
using ServerSide.Service.Interface;
using ServerSide.utils;




namespace ServerSide.Controllers
{

    [ApiController]
    [Route("userapi/[action]")]
    public class UserController
    {
        private readonly MyDBContext _myDBContext;
        private readonly IUserService _userService;
        public UserController(MyDBContext myDBContext,IUserService userService)
        {
            _myDBContext = myDBContext;
            _userService = userService;
        }
        /// <summary>
        /// 用户管理页面-获取用户数据
        /// </summary>
        /// <param name="userRequest"></param>
        /// <returns></returns>
        [HttpPost(Name = "getUserData")]
        public Result<Object> GetUserData(UserRequest userRequest)
        {

            PageInfo pageInfo = _userService.GetUsers(userRequest);
            if (pageInfo == null) {

                return Result<Object>.Error("501", "获取用户错误");
            }
            return Result<Object>.Success(pageInfo);
 
        }
        /// <summary>
        /// 用户管理页面-添加用户信息
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost(Name = "addUser")]
        public Result<Object> AddUser(UserAdd userAdd)
        {
            bool result = _userService.AddUser(userAdd);
            if (result)
            {
                return Result<Object>.Success("添加成功");
            }
            return Result<Object>.Error("501", "添加失败");
        }

        /// <summary>
        /// 用户管理页面-修改用户信息
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost(Name = "updateUserData")]
        public Result<Object> UpdateUserData(UserAdd user)
        {
            bool result = _userService.UpdateUser(user);
            if (result)
            {
                return Result<Object>.Success("修改用户成功");
            }
            return Result<Object>.Error("501", "修改用户失败");
        }

        /// <summary>
        /// 用户管理页面-修改用户信息
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpGet(Name = "changeStatusOrPassword")]
        public Result<Object> ChangeStatusOrPassword(int id, int enable, string? password)
        {
            bool v = _userService.UpdateEnableOrPassword(id, enable, password);
            if (v)
            {
                return Result<Object>.Success("修改用户成功");
            }
            return Result<Object>.Error("501", "修改用户失败");
        }

        /// <summary>
        /// 用户管理页面-删除用户信息
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost(Name = "deleteUser")]
        public Result<Object> DeleteUser(User user)
        {
            bool result = _userService.DelUser(user);
            if (result)
            {
                return Result<Object>.Success("删除用户成功");
            }
            return  Result<Object>.Error("501","删除用户失败");
        }

        /// <summary>
        /// 用户管理页面-批量删除用户信息
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost(Name = "batchDelUser")]
        public Result<Object> BatchDelUser(Object obj)
        {
            List<int>? ids = JsonConvert.DeserializeObject<List<int>>(obj.ToString());
            bool result = _userService.BatchDelUsers(ids);
            if (result)
            {
                return Result<Object>.Success("批量删除用户成功");
            }
            return Result<Object>.Error("501", "批量删除用户失败");
        }

        /// <summary>
        /// 用户管理页面-更改用户状态信息
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost(Name = "changUserEnable")]
        public string ChangUserEnable(Object? obj)
        {
            return null;
        }


        /// <summary>
        /// 个人信息中心页面
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet(Name = "getPersonInfo")]
        public Result<Object> GetPersonInfo(int userId)
        {
            if (!string.IsNullOrEmpty(userId.ToString()))
            {
                UserResponse userResponse = _userService.GetPersonInfoById(userId);
                return Result<Object>.Success(userResponse);
            }
            return Result<Object>.Error("501", "用户ID不可为空");
        }

        /// <summary>
        /// 上传头像
        /// </summary>
        /// <param name="file"></param>
        /// <param name="UserName"></param>
        /// <returns></returns>
        [HttpPost(Name = "fileupLoad")]
        public Result<Object> FileupLoad([FromForm] IFormFile file, [FromForm] string? UserName)
        {

            try
            {
                if (file == null || file.Length == 0)
                {
                    return Result<Object>.Error("501", "文件为空");
                }
                //数据库查询当前用户是否存在
                User user = _myDBContext.User.FirstOrDefault(n => n.UserName == UserName);
                if (user == null)
                {
                    return Result<Object>.Error("501", "用户不存在");
                }
                //删除源文件
                string oldPath = user.HeadPhotoPath;
                if (oldPath != null && File.Exists(oldPath))
                {
                    File.Delete(oldPath);
                }

                //创建头像路径
                string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + RandomNumber.GetRandomInt(0,100).ToString()+UserName;
                string path = Path.Combine("Resources", "Picture", "headPortrait", $"{fileName}.jpg");

                //使用文件流创建头像文件
                using (FileStream img = new FileStream(path, FileMode.Create))
                {
                    file.CopyTo(img);
                }
                //更新用户头像路径
                user.HeadPhotoPath = path;
                _myDBContext.SaveChanges();
                //返回头像路径，进行回显
                var result = new
                {
                    Path = path
                };
                return Result<Object>.Success(result);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return Result<Object>.Error("501", "头像更新失败");
            }
        }
    }
}
